import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Card, Row, Col } from 'antd';
import { EditOutlined, DeleteOutlined, ExclamationCircleOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { getTaskOverviews, updateTaskOverview, deleteTaskOverview } from '../../services/allTasksService';
import { 
  TaskOverview, 
  TaskOverviewQueryParams,
  TaskEditFormData,
  TaskType,
  taskTypes,
  getSubTypesByType,
} from './models/allTasksModels';
import { getUser } from '../../utils/auth';

const { Option } = Select;
const { TextArea } = Input;

/**
 * 任务总览页面
 */
const AllTasksPage: React.FC = () => {
  // 状态定义
  const [tasks, setTasks] = useState<TaskOverview[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [currentTask, setCurrentTask] = useState<TaskOverview | null>(null);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [searchParams, setSearchParams] = useState<TaskOverviewQueryParams>({});
  const [selectedTaskType, setSelectedTaskType] = useState<TaskType | undefined>(undefined);
  
  // 获取登录用户信息
  const userInfo = getUser();
  // 获取用户英文名
  const username = userInfo?.englishName || '';
  
  // 是否有编辑权限
  const hasEditPermission = username === 'ryanwu' || username === 'selinacchen' || username === 'janewang';
  
  // 获取任务列表
  const fetchTasks = useCallback(async (params?: TaskOverviewQueryParams) => {
    try {
      setLoading(true);
      const res = await getTaskOverviews(params);
      setTasks(res.data || []);
    } catch (error) {
      console.error('获取任务列表失败:', error);
      message.error('获取任务列表失败');
    } finally {
      setLoading(false);
    }
  }, []);
  
  // 初始化加载
  useEffect(() => {
    fetchTasks();
  }, [fetchTasks]);
  
  // 打开编辑弹窗
  const handleEdit = (record: TaskOverview) => {
    setCurrentTask(record);
    form.setFieldsValue({
      id: record.id,
      taskType: record.taskType,
      taskSubType: record.taskSubType,
      busiDepartment: record.busiDepartment,
      busiGoal: record.busiGoal,
      itDepartment: record.itDepartment,
      actualProgress: record.actualProgress,
      newIssues: record.newIssues,
      nextWeekPlan: record.nextWeekPlan,
    });
    setEditModalVisible(true);
  };
  
  // 提交编辑表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      if (!currentTask) return;
      
      const updateData: TaskEditFormData = {
        id: currentTask.id,
        taskType: values.taskType,
        taskSubType: values.taskSubType,
        busiDepartment: values.busiDepartment,
        busiGoal: values.busiGoal,
        itDepartment: values.itDepartment,
        actualProgress: values.actualProgress,
        newIssues: values.newIssues,
        nextWeekPlan: values.nextWeekPlan,
      };
      
      await updateTaskOverview(currentTask.id, updateData);
      message.success('更新成功');
      setEditModalVisible(false);
      fetchTasks();
    } catch (error) {
      console.error('更新任务失败:', error);
      message.error('更新任务失败');
    }
  };
  
  // 删除任务
  const handleDelete = async (id: string | number) => {
    try {
      await deleteTaskOverview(id);
      message.success('删除成功');
      fetchTasks();
    } catch (error) {
      console.error('删除任务失败:', error);
      message.error('删除任务失败');
    }
  };
  
  // 处理搜索
  const handleSearch = async () => {
    const values = await searchForm.validateFields();
    const params: TaskOverviewQueryParams = {};
    
    if (values.taskType) params.taskType = values.taskType;
    if (values.taskSubType) params.taskSubType = values.taskSubType;
    if (values.busiDepartment) params.busiDepartment = values.busiDepartment;
    if (values.itDepartment) params.itDepartment = values.itDepartment;
    if (values.processor) params.processor = values.processor;
    
    setSearchParams(params);
    fetchTasks(params);
  };
  
  // 重置搜索表单
  const handleResetSearch = () => {
    searchForm.resetFields();
    setSelectedTaskType(undefined);
    setSearchParams({});
    fetchTasks();
  };

  // 搜索表单任务类型变更处理
  const handleSearchTaskTypeChange = (value: TaskType) => {
    setSelectedTaskType(value);
    searchForm.setFieldsValue({ taskSubType: undefined });
  };
  
  // 编辑表单任务类型变更处理
  const handleEditTaskTypeChange = (value: TaskType) => {
    form.setFieldsValue({ taskSubType: undefined });
  };
  
  // 表格列定义
  const columns: any[] = [
    {
      title: '任务名称',
      dataIndex: 'title',
      key: 'title',
      width: 300,
    },
    {
      title: '任务类型',
      dataIndex: 'taskType',
      key: 'taskType',
      width: 120,
    },
    {
      title: '任务子类型',
      dataIndex: 'taskSubType',
      key: 'taskSubType',
      width: 150,
    },
    {
      title: '业务部门',
      dataIndex: 'busiDepartment',
      key: 'busiDepartment',
      width: 150,
    },
    {
      title: '业务目标',
      dataIndex: 'busiGoal',
      key: 'busiGoal',
      width: 250,
    },
    {
      title: 'IT部门',
      dataIndex: 'itDepartment',
      key: 'itDepartment',
      width: 150,
    },
    {
      title: '上周状态',
      dataIndex: 'lastWeekStatus',
      key: 'lastWeekStatus',
      width: 100,
      render: (status: string) => {
        const statusMap: Record<string, string> = {
          todo: '待办',
          inProgress: '进行中',
          done: '已完成',
        };
        return statusMap[status] || '-';
      },
    },
    {
      title: '当前状态',
      dataIndex: 'currentStatus',
      key: 'currentStatus',
      width: 100,
      render: (status: string) => {
        const statusMap: Record<string, string> = {
          todo: '待办',
          inProgress: '进行中',
          done: '已完成',
        };
        return statusMap[status] || '-';
      },
    },
    {
      title: '是否新项目',
      dataIndex: 'isNewProject',
      key: 'isNewProject',
      width: 100,
      render: (value: boolean) => (value ? '是' : '否'),
    },
    {
      title: '是否新完成',
      dataIndex: 'isNewlyCompleted',
      key: 'isNewlyCompleted',
      width: 100,
      render: (value: boolean) => (value ? '是' : '否'),
    },
    {
      title: '原计划',
      dataIndex: 'originalPlan',
      key: 'originalPlan',
      width: 250,
    },
    {
      title: '实际进展',
      dataIndex: 'actualProgress',
      key: 'actualProgress',
      width: 250,
    },
    {
      title: '遗留问题',
      dataIndex: 'pendingIssues',
      key: 'pendingIssues',
      width: 250,
    },
    {
      title: '新问题',
      dataIndex: 'newIssues',
      key: 'newIssues',
      width: 250,
    },
    {
      title: '下周计划',
      dataIndex: 'nextWeekPlan',
      key: 'nextWeekPlan',
      width: 250,
    },
    {
      title: '任务处理人',
      dataIndex: 'processor',
      key: 'processor',
      width: 100,
    },
  ];
  
  // 如果有编辑权限，添加操作列
  if (hasEditPermission) {
    columns.push({
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 120,
      render: (_: any, record: TaskOverview) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此任务吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="是"
            cancelText="否"
            icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
          >
            {/* <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button> */}
          </Popconfirm>
        </Space>
      ),
    });
  }
  
  return (
    <PageContainer>
      {/* 搜索表单 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={24}>
            <Col span={4}>
              <Form.Item name="taskType" label="任务类型" style={{ marginBottom: 0 }}>
                <Select 
                  placeholder="请选择任务类型" 
                  allowClear
                  onChange={handleSearchTaskTypeChange}
                >
                  {taskTypes.map(type => (
                    <Option key={type} value={type}>{type}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="taskSubType" label="任务子类型" style={{ marginBottom: 0 }}>
                <Select placeholder="请选择任务子类型" allowClear>
                  {getSubTypesByType(selectedTaskType).map(subType => (
                    <Option key={subType} value={subType}>{subType}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="busiDepartment" label="业务部门" style={{ marginBottom: 0 }}>
                <Input placeholder="请输入业务部门" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="itDepartment" label="IT部门" style={{ marginBottom: 0 }}>
                <Input placeholder="请输入IT部门" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item name="processor" label="处理人" style={{ marginBottom: 0 }}>
                <Input placeholder="请输入处理人" />
              </Form.Item>
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              <Form.Item style={{ marginBottom: 0 }}>
                <Space size="middle">
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button icon={<ReloadOutlined />} onClick={handleResetSearch}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
      
      <Table
        columns={columns}
        dataSource={tasks}
        rowKey="id"
        loading={loading}
        scroll={{ x: 'max-content' }}
        pagination={{
          pageSize: 20,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
        rowClassName={() => 'ant-table-row-custom'}
      />
      
      {/* 编辑弹窗 */}
      <Modal
        title="编辑任务"
        open={editModalVisible}
        onOk={handleSubmit}
        onCancel={() => setEditModalVisible(false)}
        width={800}
        footer={
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setEditModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" onClick={handleSubmit}>
                确认
              </Button>
            </Space>
          </div>
        }
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ 
            taskType: currentTask?.taskType,
            taskSubType: currentTask?.taskSubType,
          }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          
          <Form.Item
            name="taskType"
            label="任务类型"
            rules={[{ required: true, message: '请选择任务类型' }]}
          >
            <Select onChange={handleEditTaskTypeChange}>
              {taskTypes.map(type => (
                <Option key={type} value={type}>{type}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="taskSubType"
            label="任务子类型"
            rules={[{ required: true, message: '请选择任务子类型' }]}
          >
            <Select>
              {getSubTypesByType(form.getFieldValue('taskType')).map(subType => (
                <Option key={subType} value={subType}>{subType}</Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item
            name="busiDepartment"
            label="业务部门"
          >
            <Input placeholder="请输入业务部门" />
          </Form.Item>
          
          <Form.Item
            name="busiGoal"
            label="业务目标"
          >
            <TextArea rows={3} placeholder="请输入业务目标" />
          </Form.Item>
          
          <Form.Item
            name="itDepartment"
            label="IT部门"
          >
            <Input placeholder="请输入IT部门" />
          </Form.Item>
          
          <Form.Item
            name="actualProgress"
            label="实际进展"
          >
            <TextArea rows={3} placeholder="请输入实际进展" />
          </Form.Item>
          
          <Form.Item
            name="newIssues"
            label="新问题"
          >
            <TextArea rows={3} placeholder="请输入新问题" />
          </Form.Item>
          
          <Form.Item
            name="nextWeekPlan"
            label="下周计划"
          >
            <TextArea rows={3} placeholder="请输入下周计划" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default AllTasksPage;

/* 自定义表格行样式 */
const tableCustomStyle = `
  .ant-table-row-custom .ant-table-cell {
    white-space: normal;
    word-break: break-word;
    padding: 12px 16px;
    line-height: 1.5;
    vertical-align: top;
  }
  
  .ant-table-tbody > tr > td {
    max-width: 300px;
    white-space: normal;
    word-break: break-word;
  }
  
  .ant-table-thead > tr > th {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
`;

// 将自定义样式添加到文档中
if (typeof document !== 'undefined') {
  const styleEl = document.createElement('style');
  styleEl.innerHTML = tableCustomStyle;
  document.head.appendChild(styleEl);
} 